(function(window, document) {
    angular
        .module('app')
        .factory('WebViewJavascriptBridgeFactory', WebViewJavascriptBridgeFactory);

    WebViewJavascriptBridgeFactory.$inject = ['userAgentFactory'];

    function WebViewJavascriptBridgeFactory (userAgentFactory) {
        var service = {};

        service.init = function(callback) {
            if (window.WebViewJavascriptBridge) {
                return callback(WebViewJavascriptBridge);
            } else {
                document.addEventListener('WebviewJavascriptBridgeReady', function() {
                    callback(WebViewJavascriptBridge);
                }, false);
            }

            if (userAgentFactory.getOS() === 'ios') {
                if (window.WVJBCallbacks) {
                    return window.WVJBCallbacks.push(callback);
                }
                window.WVJBCallbacks = [callback];
                var WVJBIframe = document.createElement('iframe');
                WVJBIframe.style.display = 'none';
                WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
                document.documentElement.appendChild(WVJBIframe);
                setTimeout(function() {
                    document.documentElement.removeChild(WVJBIframe);
                }, 0);
            }
        };

        return service;
    }
})(window, document);
